package com.marktotop.service.impl;

import com.marktotop.entity.Admin;
import com.marktotop.entity.Menu;
import com.marktotop.mapper.MenuMapper;
import com.marktotop.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.marktotop.utils.AdminUtils;
import com.marktotop.utils.RedisUtil;
import com.marktotop.vo.MenusVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author marktotop
 * @since 2021-05-23
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {


    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 通过用户id查询菜单列表
     *
     * @return
     */
    @Override
    public List<Menu> getMenuByAdminId() {
        // 获取当前登录用户对象
        Integer adminId = AdminUtils.getCurrentAdmin().getId();
        // 从redis获取数据
        List<Menu> menus = (List<Menu>) redisUtil.get("menu_" + adminId);
        if (StringUtils.isEmpty(menus)){
            menus = menuMapper.getMenuByAdminId(adminId);
            // 将数据放入redis中存储
            redisUtil.set("menu_" + adminId,menus);
        }
        return menus;
    }

    /**
     * 根据角色获取相应的菜单列表
     *
     * @return
     */
    @Override
    public List<Menu> getMenusWithRoles() {
        return menuMapper.getMenusWithRoles();
    }

    /**
     * 查询所有菜单
     *
     * @return
     */
    @Override
    public List<MenusVO> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
